package com.lanyam.travel.base.service.impl;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.lanyam.travel.base.dao.*;
import com.lanyam.travel.base.entity.*;
import com.lanyam.travel.base.entity.vo.DistrRecordVo;
import com.lanyam.travel.base.entity.vo.FormReport;
import com.lanyam.travel.base.entity.vo.OrderGoodsDateVo;
import com.lanyam.travel.base.entity.vo.TravelOrderVo;
import com.lanyam.travel.base.service.ICaseWithdraService;
import com.lanyam.travel.base.service.IDistrRecordService;
import com.lanyam.travel.base.service.IOrderGoodsDateService;
import com.lanyam.travel.base.service.IOrderUserService;
import com.lanyam.travel.base.service.ITravelOrderDetailsService;
import com.lanyam.travel.base.service.ITravelOrderService;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.lanyam.travel.base.service.UserService;

import net.sf.jsqlparser.expression.operators.conditional.OrExpression;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author rosson
 * @since 2020-01-27
 */
@Service
public class TravelOrderServiceImpl implements ITravelOrderService {

	@Autowired
	private TravelOrderMapper travelOrderMapper;
	
	@Autowired
	private TravelLineMapper travelLineMapper;
	
	@Autowired
	private ScenicHotelMapper scenicHotelMapper;
	
	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private IOrderUserService orderUserService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private SupplierInfoMapper supplierInfoMapper;
	
	@Autowired
	private IOrderGoodsDateService orderGoodsDateService;
	
	@Autowired
	private IDistrRecordService distrRecordService;
	
	@Autowired
	private ICaseWithdraService caseWithdraService;
	@Autowired
	private DistrRecordMapper distrRecordMapper;
	
	@Override
	public void addOrder(TravelOrder order) {
		// TODO Auto-generated method stub
		travelOrderMapper.insert(order);
	}

	@Override
	public int queryPanicBuyCount(String panicBuyId, String userId) {
		// TODO Auto-generated method stub
		Map<String,Object> reqMap = new HashMap<String, Object>();
		reqMap.put("panic_buy_id", panicBuyId);
		reqMap.put("user_id", userId);
		List<TravelOrder> orderList = travelOrderMapper.selectByMap(reqMap);
		return orderList.size();
	}

	@Override
	public IPage<TravelOrderVo> getPageTravelOrder (Map<String, Object> queryMap, Integer page, Integer rows) {
		Page<TravelOrderVo> pageSize = new Page<TravelOrderVo>(page, rows);
		Page<TravelOrderVo> pageInfo = null;
		User currentUser = userService.getCurrentUser();
		// 判断用户身份
		String roleId = currentUser.getRoleId();
		if (roleId != null && roleId.equals("002"))
			queryMap.put("userRole", "admin");
		else
			queryMap.put("userRole", "supply");

		// 根据供应商获取列表信息
		if (currentUser == null) {
			return pageInfo;
		} else {
			SupplierInfo supplierInfo = supplierInfoMapper.getByUserId(currentUser.getId());
			if (supplierInfo == null) {
				return pageInfo;
			} else {
				queryMap.put("supplyId", supplierInfo.getId());
			}
		}
		pageInfo = travelOrderMapper.getPage(pageSize, queryMap);
		return pageInfo;
	}

	@Override
	public void addTravelOrder(TravelOrder travelOrder) {
		travelOrderMapper.insert(travelOrder);
	}

	@Override
	public void delById(String id) {
		travelOrderMapper.delById(id);
	}

	@Override
	public void exportExcel(Map<String, Object> map, HttpServletResponse response) throws Exception {
		User currentUser = userService.getCurrentUser();
		List<TravelOrderVo> list = null;
		// 判断用户身份
		String roleId = currentUser.getRoleId();
		if (roleId != null && roleId.equals("002"))
			map.put("userRole", "admin");
		else
			map.put("userRole", "supply");

		// 根据供应商获取列表信息
		if (currentUser == null) {
			list = new ArrayList<>();
		} else {
			SupplierInfo supplierInfo = supplierInfoMapper.getByUserId(currentUser.getId());
			if (supplierInfo == null) {
				list = new ArrayList<>();
			} else {
				map.put("supplyId", supplierInfo.getId());
				list = travelOrderMapper.getList(map);
			}
		}
		exportExcel(list, response);
	}

	public void exportExcel(List<TravelOrderVo> list, HttpServletResponse response) throws Exception {
		// # 设置下载项
		ServletOutputStream out = response.getOutputStream();
		String fileName = "订单统计.xlsx";
		fileName = new String(fileName.getBytes(), "ISO-8859-1");
		response.reset();
		response.setContentType("bin");
		response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

		// ## 创建excel文件
		HSSFWorkbook workbook = new HSSFWorkbook();
		String[] titles = {
				"是否为抢购", "商品名称", "下单用户", "订单状态", "订购时间", "预定使用时间", "使用时间", "费用", "预定人数", "购票数", "订票类型"
		};
		// ###创建工作簿
		HSSFSheet hssfSheet = workbook.createSheet("订单信息");
		// ### 创建表头
		HSSFRow row = hssfSheet.createRow(0);
		// #### 创建表头样式
		HSSFCellStyle hssfCellStyle = workbook.createCellStyle();
		// #### 填写表头
		HSSFCell hssfCell = null;
		for (int i = 0; i < titles.length; i++) {
			hssfCell = row.createCell(i);//列索引从0开始
			hssfCell.setCellValue(titles[i]);//列名1
			hssfCell.setCellStyle(hssfCellStyle);//列居中显示
		}
		// ### 填写数据
		// 生成查询条件
		for (int i=0; i<list.size(); i++) {
			TravelOrderVo travelOrderVo = list.get(i);
			HSSFRow dataRow = hssfSheet.createRow(i + 1);
			String isPanic = travelOrderVo.getIsPanic();
			String goodsName = travelOrderVo.getGoodsName();
			String userName = travelOrderVo.getUserName();
			Integer payStatus = travelOrderVo.getPayStatus();
			String status = payStatus==null?"未填写":payStatus==0?"未付款":payStatus==1?"已付款":payStatus==2?"退款":"失效订单";
			Date orderDateStamp = travelOrderVo.getOrderTime();
			String orderDate = orderDateStamp==null?"未填写":transDateToStr(orderDateStamp);
			Date bookDateStamp = travelOrderVo.getBookUseDate();
			String bookDate = bookDateStamp==null?"未填写":transDateToStr(bookDateStamp);
			Date useDateStamp = travelOrderVo.getBookEndDate();
			String useDate = useDateStamp==null?"未填写":transDateToStr(useDateStamp);
			BigDecimal costBigDecimal = travelOrderVo.getRealAmount();
			String cost = costBigDecimal==null?"未填写":costBigDecimal.toString();
//			Integer personNumInt = travelOrderVo.getPersonNum();
//			String personNum = personNumInt==null?"未填写":personNumInt.toString();
//			Integer ticketNumInt = travelOrderVo.getTicketNum();
//			String ticketNum = ticketNumInt==null?"未填写":ticketNumInt.toString();
//			Integer typeInt = travelOrderVo.getType();
//			String type = typeInt==null?"未填写":typeInt==0?"成人":typeInt==1?"儿童":"团体";
			dataRow.createCell(0).setCellValue(transEmptyStr(isPanic));
			dataRow.createCell(1).setCellValue(transEmptyStr(goodsName));
			dataRow.createCell(2).setCellValue(transEmptyStr(userName));
			dataRow.createCell(3).setCellValue(transEmptyStr(status));
			dataRow.createCell(4).setCellValue(transEmptyStr(orderDate));
			dataRow.createCell(5).setCellValue(transEmptyStr(bookDate));
			dataRow.createCell(6).setCellValue(transEmptyStr(useDate));
			dataRow.createCell(7).setCellValue(transEmptyStr(cost));
//			dataRow.createCell(8).setCellValue(transEmptyStr(personNum));
//			dataRow.createCell(9).setCellValue(transEmptyStr(ticketNum));
//			dataRow.createCell(10).setCellValue(transEmptyStr(type));
		}
		// 拓宽宽度
		HSSFRow dataRowLast = hssfSheet.createRow(list.size() + 2);
		dataRowLast.createCell(0).setCellValue("--------------------------");
		dataRowLast.createCell(1).setCellValue("--------------------------");
		dataRowLast.createCell(2).setCellValue("--------------------------");
		dataRowLast.createCell(3).setCellValue("--------------------------");
		dataRowLast.createCell(4).setCellValue("--------------------------");
		dataRowLast.createCell(5).setCellValue("--------------------------");
		dataRowLast.createCell(6).setCellValue("--------------------------");
		dataRowLast.createCell(7).setCellValue("--------------------------");
		dataRowLast.createCell(8).setCellValue("--------------------------");
		dataRowLast.createCell(9).setCellValue("--------------------------");
		dataRowLast.createCell(10).setCellValue("--------------------------");
		// 设置自适应
		for (int i=0; i<titles.length; i++) {
			hssfSheet.autoSizeColumn(i);
		}
		// excel文件写入到响应
		workbook.write(out);
	}

	/**
	 * 将空字符串转换为指定的占位符
	 * @param str
	 * @return
	 */
	private String transEmptyStr(String str) {
		return StringUtils.isEmpty(str)?"未填写":str;
	}

	/**
	 * 将日期转换成指定格式字符串
	 * @param date
	 * @return
	 */
	private String transDateToStr(Date date) {
		if(date == null)
			return "未填写";
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
		String dateStr = simpleDateFormat.format(date);
		return dateStr;
	}
	
	@Override
	public Map<String, Object> paywxr(HttpServletRequest request) {
		// TODO Auto-generated method stub
		
		
		
		return null;
	}

	@Override
	public TravelOrderVo getOrderById(String orderId) {
		// TODO Auto-generated method stub
			TravelOrder order = travelOrderMapper.selectById(orderId);
			TravelOrderVo orderVo = new TravelOrderVo();
//			BeanUtils.copyProperties(orderVo, order);
			orderVo.setId(order.getId());
			orderVo.setOrderType(order.getOrderType());
			orderVo.setProductId(order.getProductId());
			orderVo.setOrderUserid(order.getOrderUserid());
			orderVo.setOrderUsername(order.getOrderUsername());
			orderVo.setOrderTime(order.getOrderTime());
			orderVo.setOverrdueTime(order.getOverrdueTime());
			orderVo.setOrderAmount(order.getOrderAmount());
			orderVo.setContact(order.getContact());
			orderVo.setTelephone(order.getTelephone());
			orderVo.setRealAmount(order.getRealAmount());
			orderVo.setPayAmount(order.getPayAmount());
			orderVo.setPayStatus(order.getPayStatus());
			orderVo.setPayTime(order.getPayTime());
			orderVo.setRemarks(order.getRemarks());
			orderVo.setRandomCode(order.getRandomCode());
			orderVo.setBookUseDate(order.getBookUseDate());
			orderVo.setBookEndDate(order.getBookEndDate());
			orderVo.setTripStatus(order.getTripStatus());
			orderVo.setTripTime(order.getTripTime());
			orderVo.setVerifyStatus(order.getVerifyStatus());
			orderVo.setVerifyUserId(order.getVerifyUserId());
			orderVo.setVerifyTime(order.getVerifyTime());
			orderVo.setConfirmUserId(order.getConfirmUserId());
			orderVo.setConfirmTime(order.getConfirmTime());
			orderVo.setSupplyId(order.getSupplyId());
			if(!StringUtils.isEmpty(orderVo.getProductId()))
			{
				Product product = getProductByOrderId(orderVo.getProductId());
				orderVo.setProduct(product);
				if(null != product)
				{
					List<OrderGoodsDateVo> datePriceList = new ArrayList<OrderGoodsDateVo>();
					if(product.getProductType() == 1)
					{
						//获取酒店房间类型
						datePriceList = orderGoodsDateService.getHotelDatePrice(orderId);
					}
					else
					{
						datePriceList = orderGoodsDateService.getScenicDatePrice(orderId);
					}
					orderVo.setDatePriceList(datePriceList);
				}
			}
			if(StringUtils.isEmpty(orderVo.getOrderUserid()))
			{
				User user = userMapper.selectById(order.getOrderUserid());
//			user.setPassword("");
				orderVo.setUserName(user.getName());
			}
			List<OrderUser> orderUsers = orderUserService.getOrderUserByOrderId(orderVo.getId());
			orderVo.setOrderUserList(orderUsers);
			
			
			//封装分销信息
			List<DistrRecordVo> records = new ArrayList<DistrRecordVo>();
			if(orderVo.getVerifyStatus() == 1 || orderVo.getVerifyStatus() == 3)
			{
				//待一审(1)或二审驳回(3)
				records = caseWithdraService.calcDistrRecord(orderId);
			}
			else if(orderVo.getVerifyStatus() == 2 || orderVo.getVerifyStatus() == 4)
			{
				//待二审(2)和二审通过(4)
				records = distrRecordService.getRecordsByOrderId(orderId);
			}
			
			orderVo.setDistrRecordList(records);
			return orderVo;
	}

	@Override
	public Product getProductByOrderId(String goodsId) {
		// TODO Auto-generated method stub
		Product product = travelLineMapper.selectById(goodsId);
		if(null == product)
		{
			product = scenicHotelMapper.selectById(goodsId);
		}
		return product;
	}

	@Override
	public void deleteOrder(String orderId) {
		// TODO Auto-generated method stub
		travelOrderMapper.deleteById(orderId);
		//关联删除订单详细，日历价格，游客信息
	}
	/**
	  * 获取订单分页信息
	  * reqMap中的key:goodsId线路/景点/酒店id;userId 下单人id;status 0未付款，1已付款，2未出行，3已出行，4退款;
	  * @return
	  */
	@Override
	public Page<TravelOrderVo> queryOrderPage(int pageNum, int pageSize, String userId,Map<String, Object> reqMap) {
		// TODO Auto-generated method stub
		User user = userMapper.selectById(userId);
		String supplyId = user.getSupplyId();
		Map<String,Object> paraMap = new HashMap<String, Object>();
		//supplyId不为空，则是供应商查询自己的订单，为空的话是管理员查询所有订单
		if(!StringUtils.isEmpty(supplyId))
		{
			//供应商
			paraMap.put("supplyId", supplyId);
		}
		//订单号
		String orderId = reqMap.get("orderId")!=null ?reqMap.get("orderId").toString():null;
		if(!StringUtils.isEmpty(orderId))
		{
			paraMap.put("id", orderId);
		}
		//订单状态
		String payStatus = reqMap.get("payStatus")!=null ?reqMap.get("payStatus").toString():null;
		if(!StringUtils.isEmpty(payStatus))
		{
			paraMap.put("payStatus", payStatus);
		}
		String tripStatus = reqMap.get("tripStatus")!=null ?reqMap.get("tripStatus").toString():null;
		if(!StringUtils.isEmpty(tripStatus))
		{
			paraMap.put("tripStatus", tripStatus);
		}
		String verifyStatus = reqMap.get("verifyStatus")!=null ?reqMap.get("verifyStatus").toString():null;
		if(!StringUtils.isEmpty(verifyStatus))
		{
			paraMap.put("verifyStatus", verifyStatus);
		}
		//开始日期-结束日期
		String startDate = reqMap.get("startDate")!=null ?reqMap.get("startDate").toString():null;
		if(!StringUtils.isEmpty(startDate))
		{
			paraMap.put("startDate", startDate);
		}
		String endDate = reqMap.get("endDate")!=null ?reqMap.get("endDate").toString():null;
		if(!StringUtils.isEmpty(endDate))
		{
			paraMap.put("endDate", endDate);
		}
		//商品名称
		String productName = reqMap.get("productName")!=null ?reqMap.get("productName").toString():null;
		if(!StringUtils.isEmpty(productName))
		{
			paraMap.put("productName", productName);
		}
		//订单类型
		String productType = reqMap.get("productType")!=null ?reqMap.get("productType").toString():null;
		if(!StringUtils.isEmpty(productType))
		{
			paraMap.put("productType", productType);
		}
		//订单类型
		String randomCode = reqMap.get("randomCode")!=null ?reqMap.get("randomCode").toString():null;
		if(!StringUtils.isEmpty(randomCode))
		{
			paraMap.put("randomCode", randomCode);
		}
		Page<TravelOrderVo> page = new Page<TravelOrderVo>(pageNum,pageSize);
		Page<TravelOrderVo> ipage = travelOrderMapper.getPage(page, paraMap);
		return ipage;
	}

	@Override
	public void examFirst(TravelOrderVo orderVo) {
		// 限定审核状态修改范围
		TravelOrder originOrder = queryOrderById(orderVo.getId());
		//TODO修改值
		originOrder.setVerifyStatus(2);
		originOrder.setVerifyTime(new Date());
		User currentUser = userService.getCurrentUser();
		originOrder.setVerifyUserId(currentUser.getId());
		originOrder.setDistrUserId(orderVo.getDistrUserId());
		originOrder.setContact(orderVo.getContact());
		originOrder.setTelephone(orderVo.getTelephone());
		
		travelOrderMapper.updateById(originOrder);
		//先删除分销记录，再添加进去，第一次审核后会添加，但二审驳回再重新一审后，不知道数据有没有记录，所以先删除再重新添加
		distrRecordService.deleteByOrderId(orderVo.getId());
		List<DistrRecordVo> distrRecordVos = orderVo.getDistrRecordList();
		if(null != distrRecordVos && distrRecordVos.size() > 0)
		{
			DistrRecord record;
			for (DistrRecordVo recordVo : distrRecordVos) {
				record = new DistrRecord();
				record.setId(recordVo.getId());
				record.setAmount(recordVo.getAmount());
				record.setCreateTime(recordVo.getCreateTime());
				record.setUserId(recordVo.getUserId());
				record.setDistUserId(recordVo.getDistUserId());
				record.setOrderId(recordVo.getOrderId());
				record.setRatio(recordVo.getAmount().divide(originOrder.getRealAmount(), 4, RoundingMode.HALF_UP).toString());
				record.setNewAmount(recordVo.getNewAmount());
				record.setOldAmount(recordVo.getOldAmount());
				distrRecordService.addDistrRecord(record);
			}
		}
		travelOrderMapper.updateById(originOrder);
	}

	@Override
	public void examSecond(TravelOrder travelOrder) {
		TravelOrder travelOrderDB = travelOrderMapper.selectById(travelOrder.getId());
//		travelOrderDB.setExamStatus(travelOrder.getExamStatus());
		travelOrderMapper.updateById(travelOrderDB);
		// TODO 第二次审核完数据后的后续操作
	}

	@Override
	public Page<TravelOrderVo> queryOrderPageByUserId(Map<String,Object> reqMap) {
		// TODO Auto-generated method stub
		Integer pageNum = Integer.parseInt(reqMap.get("page").toString());
		Integer pageSize = Integer.parseInt(reqMap.get("pageSize").toString());
		String userId = reqMap.get("userId").toString();
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("userId", userId);
		String payStatus = reqMap.get("payStatus")!=null?reqMap.get("payStatus").toString():"";
		if(!StringUtils.isEmpty(payStatus))
		{
			map.put("payStatus", payStatus);
		}
		String tripStatus = reqMap.get("tripStatus")!=null?reqMap.get("tripStatus").toString():"";
		if(!StringUtils.isEmpty(tripStatus))
		{
			map.put("tripStatus", tripStatus);
		}
		String orderType = reqMap.get("orderType")!=null?reqMap.get("orderType").toString():"";
		if(!StringUtils.isEmpty(orderType))
		{
			map.put("orderType", orderType);
		}
//		String refundSatus = reqMap.get("refundSatus");
//		if(!StringUtils.isEmpty(refundSatus))
//		{
//			map.put("refundSatus", refundSatus);
//		}
		Page<TravelOrderVo> page = new Page<TravelOrderVo>(pageNum, pageSize);
		Page<TravelOrderVo> pageInfo = travelOrderMapper.getPage(page, map);
		
		return pageInfo;
	}

	@Override
	public Map<String, List<Object>> getOrderCountByDays(String userId,Date startDate, Date endDate) {
		// TODO Auto-generated method stub
		Map<String,List<Object>> returnResult = new HashMap<String, List<Object>>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
		String startTime = sdf.format(startDate);
		String endTime = sdf.format(endDate);
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(startDate);
		calendar.set(Calendar.HOUR_OF_DAY,0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		List<Object> dateList = new ArrayList<Object>();
		while(calendar.getTime().getTime()<=endDate.getTime())
		{
			dateList.add(sdf.format(calendar.getTime()));
			calendar.add(Calendar.DAY_OF_YEAR, 1);
		}
		returnResult.put("xAxis", dateList);
		
		Map<String,String> reqMap = new HashMap<String, String>();
		reqMap.put("startDate", startTime);
		reqMap.put("endDate", endTime);
		
		User user = userMapper.selectById(userId);
		String supplyId = user.getSupplyId();
		if(!StringUtils.isEmpty(supplyId))
		{
			reqMap.put("supplyId", supplyId);
		}
		
		List<FormReport> allReport = travelOrderMapper.getOrderCountByDays(reqMap);
		List<Object> countList = new ArrayList<Object>();
		Map<String,Integer> dataMap = new HashMap<String, Integer>();
		for (FormReport formReport : allReport) {
			dataMap.put(formReport.getStrKey(), formReport.getCount());
		}
		for (Object object : dateList) {
			if(dataMap.containsKey(object))
			{
				countList.add(dataMap.get(object));
			}
			else
			{
				countList.add(0);
			}
		}
		returnResult.put("allReport", countList);
		
		reqMap.put("goodsType", "0");
		List<FormReport> scenicReport = travelOrderMapper.getOrderCountByDays(reqMap);
		countList = new ArrayList<Object>();
		dataMap = new HashMap<String, Integer>();
		for (FormReport formReport : scenicReport) {
			dataMap.put(formReport.getStrKey(), formReport.getCount());
		}
		for (Object object : dateList) {
			if(dataMap.containsKey(object))
			{
				countList.add(dataMap.get(object));
			}
			else
			{
				countList.add(0);
			}
		}
		returnResult.put("scenicReport", countList);
		
		reqMap.put("goodsType", "1");
		List<FormReport> hotelReport = travelOrderMapper.getOrderCountByDays(reqMap);
		countList = new ArrayList<Object>();
		dataMap = new HashMap<String, Integer>();
		for (FormReport formReport : hotelReport) {
			dataMap.put(formReport.getStrKey(), formReport.getCount());
		}
		for (Object object : dateList) {
			if(dataMap.containsKey(object))
			{
				countList.add(dataMap.get(object));
			}
			else
			{
				countList.add(0);
			}
		}
		returnResult.put("hotelReport", countList);
		
		reqMap.put("goodsType", "2");
		List<FormReport> outerLineReport = travelOrderMapper.getOrderCountByDays(reqMap);
		countList = new ArrayList<Object>();
		dataMap = new HashMap<String, Integer>();
		for (FormReport formReport : outerLineReport) {
			dataMap.put(formReport.getStrKey(), formReport.getCount());
		}
		for (Object object : dateList) {
			if(dataMap.containsKey(object))
			{
				countList.add(dataMap.get(object));
			}
			else
			{
				countList.add(0);
			}
		}
		returnResult.put("outerLineReport", countList);
		
		reqMap.put("goodsType", "3");
		List<FormReport> innerLineReport = travelOrderMapper.getOrderCountByDays(reqMap);
		countList = new ArrayList<Object>();
		dataMap = new HashMap<String, Integer>();
		for (FormReport formReport : innerLineReport) {
			dataMap.put(formReport.getStrKey(), formReport.getCount());
		}
		for (Object object : dateList) {
			if(dataMap.containsKey(object))
			{
				countList.add(dataMap.get(object));
			}
			else
			{
				countList.add(0);
			}
		}
		returnResult.put("innerLineReport", countList);
		
		return returnResult;
	}

	@Override
	public Map<String,Integer> getOrderNumByMonth(String userId,Date date) {
		// TODO Auto-generated method stub
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM");
		String month = sdf.format(date);
		Map<String,String> reqMap = new HashMap<String, String>();
		
		User user = userMapper.selectById(userId);
		String supplyId = user.getSupplyId();
		if(!StringUtils.isEmpty(supplyId))
		{
			reqMap.put("supplyId", supplyId);
		}
		reqMap.put("month", month);
		//获取所有订单数 
		Integer totalOrder = travelOrderMapper.getorderCountByStatus(reqMap);
		//获取已使用订单数trip_status
		reqMap.put("tripStatus", "1");
		Integer usedOrder = travelOrderMapper.getorderCountByStatus(reqMap);
		//获取未使用订单数
		reqMap.put("tripStatus", "0");
		Integer unuseOrder = travelOrderMapper.getorderCountByStatus(reqMap);
		//获取退款订单数
		reqMap.remove("tripStatus");
		reqMap.put("payStatus", "2");
		Integer refundOrder = travelOrderMapper.getorderCountByStatus(reqMap);
		//获取待审核订单数
		reqMap.remove("payStatus");
		reqMap.put("verifyStatus", "2");
		Integer unverifyOrder = travelOrderMapper.getorderCountByStatus(reqMap);
		Map<String,Integer> resultMap = new HashMap<String, Integer>();
		resultMap.put("totalOrder", totalOrder);
		resultMap.put("usedOrder", usedOrder);
		resultMap.put("unuseOrder", unuseOrder);
		resultMap.put("refundOrder", refundOrder);
		resultMap.put("unverifyOrder", unverifyOrder);
		//获取酒店数/景区数/线路数
		int lineCount = travelLineMapper.getLineCount();
		resultMap.put("lineCount", lineCount);
		int scenicCount = scenicHotelMapper.getProductCount(0);
		resultMap.put("scenicCount", scenicCount);
		int hotelCount = scenicHotelMapper.getProductCount(1);
		resultMap.put("hotelCount", hotelCount);
		//当月订单数
		resultMap.put("orderCountInMonth", totalOrder);
		
		
		Map<String,String> map = new HashMap<String, String>();
		if(!StringUtils.isEmpty(supplyId))
		{
			map.put("supplyId", supplyId);
		}
		//总计订单数
		Integer allOrderCount = travelOrderMapper.getAllOrderCount(map);
		resultMap.put("allOrderCount", allOrderCount);
		//总计订单总金额
		Integer allOrderAmount = travelOrderMapper.getAllOrderAmount(map);
		resultMap.put("orderAmountInMonth", allOrderAmount);
		
		//当月订单总金额
		map.put("month", month);
		Integer orderAmountInMonth = travelOrderMapper.getOrderAmountInMonth(map);
		resultMap.put("orderAmountInMonth", orderAmountInMonth);
		return resultMap;
	}

	@Override
	public boolean checkOrder(String orderId) {
		// TODO Auto-generated method stub
		//思路：根据orderId获取订单详情，根据订单中的景点id获取景点详情，如果景点中的供应商id和supplyId一致并且订单中的随机码和randomCode相同，则验票通过，否则失败
		User loginUser = userService.getCurrentUser();
		TravelOrder order = queryOrderById(orderId);
		if(null == order)
		{
			return false;
		}
		boolean canCheckOrder = false;
		//平台管理员可以
		if(null != loginUser && StringUtils.isEmpty(loginUser.getSupplyId()) && !StringUtils.isEmpty(loginUser.getRoleId()))
		{
			canCheckOrder = true;
		}
		//对应的供应商可以
		if(loginUser.getSupplyId().equals(order.getSupplyId()))
		{
			canCheckOrder = true;
		}
		if(canCheckOrder)
		{
			order.setTripStatus(1);
			order.setVerifyStatus(1);
			order.setTripTime(new Date());
			travelOrderMapper.updateById(order);
			return true;
		}
		return false;
	}

	@Override
	public TravelOrder queryOrderById(String orderId) {
		// TODO Auto-generated method stub
		TravelOrder order = travelOrderMapper.selectById(orderId);
		return order;
	}

	@Override
	public List<TravelOrderVo> searchCheckOrder(Map<String, Object> reqMap) {
		// TODO Auto-generated method stub
		String userId = (String) reqMap.get("userId");
		User user = userMapper.selectById(userId);
		String supplyId = user.getSupplyId();
		Map<String,Object> paraMap = new HashMap<String, Object>();
		//supplyId不为空，则是供应商查询自己的订单，为空的话是管理员查询所有订单
		if(!StringUtils.isEmpty(supplyId))
		{
			//供应商
			paraMap.put("supplyId", supplyId);
		}
		//订单号
		String checkCode = reqMap.get("checkCode")!=null ?reqMap.get("checkCode").toString():null;
		if(!StringUtils.isEmpty(checkCode))
		{
			paraMap.put("checkCode", checkCode);
		}
		//开始日期-结束日期
		String startDate = reqMap.get("startDate")!=null ?reqMap.get("startDate").toString():null;
		if(!StringUtils.isEmpty(startDate))
		{
			paraMap.put("startDate", startDate);
		}
		String endDate = reqMap.get("endDate")!=null ?reqMap.get("endDate").toString():null;
		if(!StringUtils.isEmpty(endDate))
		{
			paraMap.put("endDate", endDate);
		}
		List<TravelOrderVo> orders = travelOrderMapper.searchCheckOrder(paraMap);
		return orders;
	}

	@Override
	public Page<TravelOrderVo> queryExamOrderByPage(Integer pageNum, Integer pageSize, String userId,
			Map<String, Object> reqMap) {
		// TODO Auto-generated method stub
		User user = userMapper.selectById(userId);
		String supplyId = user.getSupplyId();
		Map<String,Object> paraMap = new HashMap<String, Object>();
		//supplyId不为空，则是供应商查询自己的订单，为空的话是管理员查询所有订单
		if(!StringUtils.isEmpty(supplyId))
		{
			//供应商
			paraMap.put("supplyId", supplyId);
		}
		//订单号
		String orderId = reqMap.get("orderId")!=null ?reqMap.get("orderId").toString():null;
		if(!StringUtils.isEmpty(orderId))
		{
			paraMap.put("id", orderId);
		}
		//订单状态
		String payStatus = reqMap.get("payStatus")!=null ?reqMap.get("payStatus").toString():null;
		if(!StringUtils.isEmpty(payStatus))
		{
			paraMap.put("payStatus", payStatus);
		}
		//开始日期-结束日期
		String startDate = reqMap.get("startDate")!=null ?reqMap.get("startDate").toString():null;
		if(!StringUtils.isEmpty(startDate))
		{
			paraMap.put("startDate", startDate);
		}
		String endDate = reqMap.get("endDate")!=null ?reqMap.get("endDate").toString():null;
		if(!StringUtils.isEmpty(endDate))
		{
			paraMap.put("endDate", endDate);
		}
		//商品名称
		String productName = reqMap.get("productName")!=null ?reqMap.get("productName").toString():null;
		if(!StringUtils.isEmpty(productName))
		{
			paraMap.put("productName", productName);
		}
		//订单类型
		String productType = reqMap.get("productType")!=null ?reqMap.get("productType").toString():null;
		if(!StringUtils.isEmpty(productType))
		{
			paraMap.put("productType", productType);
		}
		Page<TravelOrderVo> page = new Page<TravelOrderVo>(pageNum,pageSize);
		Page<TravelOrderVo> ipage = travelOrderMapper.getExamOrderPage(page, paraMap);
		return ipage;
	}

	@Override
	public Page<TravelOrderVo> queryFinanceOrderByPage(Integer pageNum, Integer pageSize, Map<String, Object> reqMap) {
		// TODO Auto-generated method stub
		User user = userService.getCurrentUser();
		Map<String,Object> paraMap = new HashMap<String, Object>();
		//supplyId不为空，则是供应商查询自己的订单，为空的话是管理员查询所有订单
		if(null!= user && !StringUtils.isEmpty(user.getSupplyId()))
		{
			//供应商
			paraMap.put("supplyId", user.getSupplyId());
		}
		Page<TravelOrderVo> page = new Page<TravelOrderVo>(pageNum,pageSize);
		Page<TravelOrderVo> ipage = travelOrderMapper.queryFinanceOrderByPage(page, paraMap);
		//查询分销记录表，计算出每个订单的利润
		List<TravelOrderVo> records = ipage.getRecords();
		for (TravelOrderVo travelOrderVo : records) {
			double cost = 0;
			List<DistrRecordVo> recordsInOrder = distrRecordService.getRecordsByOrderId(travelOrderVo.getId());
			if(null != recordsInOrder && recordsInOrder.size() > 0)
			{
				for (DistrRecord distrRecord : recordsInOrder) {
					cost += distrRecord.getAmount().doubleValue();
				}
			}
			double benifit = 0;
			if(null != travelOrderVo.getRealAmount())
			{
				benifit = travelOrderVo.getRealAmount().doubleValue() - cost;
			}
			travelOrderVo.setBenifit(benifit);
		}
		return ipage;
	}

	@Override
	public Page<TravelOrderVo> getDistrOrderList(Integer page, Integer pageSize, Map<String, Object> map) {
		User currentUser = userService.getCurrentUser();
		Page<TravelOrderVo> orderPage = queryOrderPage(page, pageSize, currentUser.getId(), map);
		List<TravelOrderVo> orderList = orderPage.getRecords();
		for (TravelOrderVo travelOrderVo : orderList) {
			String id = travelOrderVo.getId();
			List<DistrRecordVo> listByOrderId = distrRecordMapper.getListByOrderId(id);
			travelOrderVo.setDistrRecordList(listByOrderId);
		}
		return orderPage;
	}

	@Override
	public void updateOrder(TravelOrder order) {
		// TODO Auto-generated method stub
		travelOrderMapper.updateById(order);
	}

}
